﻿using Apps.Common;
using Apps.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Linq.Expressions;
using Apps.Locale;
using System.Data.Common;
using System.Data;
using Apps.BLL.Core;
using System.Runtime.ConstrainedExecution;
using System.Runtime.InteropServices.ComTypes;
using Apps.DAL;
using Apps.DAL.LMS;
using Apps.DAL.SelfRcRelated;
using Apps.Models.CustomModels;

namespace Apps.BLL.LMS
{
    public partial class LMS_TESTDATA_AUDITBLL
    {
        LMS_TESTDATA_AUDIT_Repository dal = new LMS_TESTDATA_AUDIT_Repository();
        public virtual V_LMS_RESULT_AUDITModel GetVItem(Expression<Func<V_LMS_RESULT_AUDIT, bool>> whereLambda)
        {
            using (DBContainer db = new DBContainer())
            {
                V_LMS_RESULT_AUDIT entity = db.V_LMS_RESULT_AUDIT.Where(whereLambda).SingleOrDefault();
                if (entity == null) return null;

                V_LMS_RESULT_AUDITModel model = new V_LMS_RESULT_AUDITModel();
                model.AUDIT_ID = entity.AUDIT_ID;
                model.TEST_CODE = entity.TEST_CODE;
                model.UPDATE_TIME = entity.UPDATE_TIME;
                model.STYPE = entity.STYPE;
                model.STYPE_STR = entity.STYPE_STR;
                model.TEST_TYPE = entity.TEST_TYPE;
                model.TEST_TYPE_STR = entity.TEST_TYPE_STR;
                model.TEST_MODE_STR = entity.TEST_MODE_STR;
                model.MT = entity.MT;
                model.MAD = entity.MAD;
                model.AAD = entity.AAD;
                model.AD = entity.AD;
                model.AAR = entity.AAR;
                model.VAD = entity.VAD;
                model.VD = entity.VD;
                model.VAR = entity.VAR;
                model.VDAF = entity.VDAF;
                model.FCAD = entity.FCAD;
                model.CRC = entity.CRC;
                model.STAD = entity.STAD;
                model.STD = entity.STD;
                model.STAR = entity.STAR;
                model.STDAF = entity.STDAF;
                model.QBAD = entity.QBAD;
                model.QGRAD = entity.QGRAD;
                model.QGRD = entity.QGRD;
                model.QNETAR_MJ = entity.QNETAR_MJ;
                model.QNETAR_KCAL = entity.QNETAR_KCAL;
                model.HAD = entity.HAD;
                model.APPROVAL_STATUS = entity.APPROVAL_STATUS;
                model.TEMPLATE_ID = entity.TEMPLATE_ID;
                model.AUDIT_USER_ID = entity.AUDIT_USER_ID;
                model.AUDIT_TIME = entity.AUDIT_TIME;

                return model;
            }
        }

        public List<V_LMS_RESULT_AUDITModel> GetList(ref GridPager pager, string testcode, string batch)
        {
            using (DBContainer db = new DBContainer())
            {
                IQueryable<V_LMS_RESULT_AUDIT> queryData;
                if (!string.IsNullOrEmpty(batch))
                {
                    queryData = (from r in db.V_LMS_RESULT_AUDIT
                                 join c in db.V_FLOW_STEPINFO on r.AUDIT_ID equals c.ID
                                 join s in db.LMS_COLLECTSAMPLE on r.TEST_CODE equals s.TEST_CODE
                                 where r.APPROVAL_STATUS > 1 && s.BATCH_CODE == batch
                                 select r).Distinct();
                }
                else
                {
                    queryData = (from r in db.V_LMS_RESULT_AUDIT
                                 join c in db.V_FLOW_STEPINFO on r.AUDIT_ID equals c.ID
                                 join s in db.LMS_COLLECTSAMPLE on r.TEST_CODE equals s.TEST_CODE
                                 where r.APPROVAL_STATUS > 1
                                 select r).Distinct();
                }
                if (!string.IsNullOrEmpty(testcode))
                {
                    queryData = queryData.Where(m => m.TEST_CODE == testcode);
                }

                //if (!string.IsNullOrEmpty(enddate))
                //{
                //    DateTime dEndDate = DateTime.ParseExact(enddate, "yyyy-MM-dd", null);
                //    queryData = queryData.Where(m => m.UPDATE_TIME <= dEndDate);
                //}

                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return TransHelper.TransExpList<V_LMS_RESULT_AUDIT, V_LMS_RESULT_AUDITModel>(queryData.ToList());

            }
        }

        public List<V_LMS_RESULT_AUDITModel> GetList(ref GridPager pager, string testcode, string startdate, string enddate)
        {
            using (DBContainer db = new DBContainer())
            {
                IQueryable<V_LMS_RESULT_AUDIT> queryData = (from r in db.V_LMS_RESULT_AUDIT
                                                            join c in db.V_FLOW_STEPINFO
                                                            on r.AUDIT_ID equals c.ID
                                                            where r.APPROVAL_STATUS > 1
                                                            select r).Distinct();
                if (!string.IsNullOrEmpty(testcode))
                {
                    queryData = queryData.Where(m => m.TEST_CODE == testcode);
                }
                if (!string.IsNullOrEmpty(startdate))
                {
                    DateTime dStartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);
                    queryData = queryData.Where(m => m.UPDATE_TIME >= dStartDate);
                }
                if (!string.IsNullOrEmpty(enddate))
                {
                    DateTime dEndDate = DateTime.ParseExact(enddate, "yyyy-MM-dd", null);
                    queryData = queryData.Where(m => m.UPDATE_TIME <= dEndDate);
                }

                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                return TransHelper.TransExpList<V_LMS_RESULT_AUDIT, V_LMS_RESULT_AUDITModel>(queryData.ToList());

            }
        }

        public bool DELETE_LMS_AUDITDATA(ref ValidationErrors errors, string audit_id)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    var model = db.V_STATS_LMS_PLAN_RESULT.Where(p => p.AUDIT_ID == audit_id).ToList();
                    if (model == null) return false;

                    var ret = db.ExecuteProduce("PCK_LMSDATAINFO.DELETE_LMS_AUDITDATA",
                                            db.CreateInParameter("P_TESTCODE", DbType.AnsiString, model[0].TEST_CODE),
                                            db.CreateInParameter("P_UPDATETIME", DbType.AnsiString, model[0].UPDATE_TIME.ToString()),
                                            db.CreateOutParameter("ERRCODE", DbType.AnsiString, 10),
                                            db.CreateOutParameter("ERRMSG", DbType.AnsiString, 100)
                                            );
                    return ret["ERRCODE"].ToString() == "0" ? true : false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public bool UPDATE_LMS_AUDITDATA(ref ValidationErrors errors, V_LMS_RESULT_AUDIT model)
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    var ret = db.ExecuteProduce("PCK_LMSDATAINFO.SELECT_LMS_CONFIRMEDDATA",
                                         db.CreateInParameter("P_TESTCODE", DbType.AnsiString, model.TEST_CODE),
                                         db.CreateInParameter("P_UPDATETIME", DbType.AnsiString, model.UPDATE_TIME.ToString()),
                                         db.CreateInParameter("P_TESTINDEXS", DbType.AnsiString, model.TEST_MODE_STR),
                                         db.CreateInParameter("P_USERID", DbType.AnsiString, model.AUDIT_USER_ID),
                                         db.CreateOutParameter("ERRCODE", DbType.AnsiString, 10),
                                         db.CreateOutParameter("ERRMSG", DbType.AnsiString, 100)
                                         );
                    return ret["ERRCODE"].ToString() == "0" ? true : false;
                }
            }
            catch (Exception ex)
            {
                errors.Add(ex.Message);
                ExceptionHander.WriteException(ex);
                return false;
            }
        }

        public string UPDATE_LMS_AUDITDATA( V_LMS_RESULT_AUDIT model)
        {
            try
            {
                return "";
            }
            catch (Exception ex)
            {
                ExceptionHander.WriteException(ex);
                return "";
            }
        }

        //: DbContext<YANX_RECORD>
        public List<TestDataOutPutModel> GetSugarList(TestDataQuertParaModel model, ref int totalCount, bool isPage = true)
        {
            return dal.GetSugarList(model, ref totalCount, isPage);

        }

        /// <summary>
        /// 获取当前批次下面得所有车牌信息
        /// </summary>
        /// <param name="BatchCode"></param>
        /// <returns></returns>
        public List<V_RC_SAMPLING> GetChepai(string BatchCode)
        {
            return dal.GetChepai(BatchCode);
        }

        /// <summary>
        /// 获取原始数据
        /// </summary>
        /// <param name="BatchCode"></param>
        /// <returns></returns>
        public List<V_LMS_TESTDATA_CONFIRMED> GetOriRecord(string testCode)
        {
            return dal.GetOriRecord(testCode);
        }

        /// <summary>
        /// 备份审核前的数据
        /// </summary>
        /// <param name="testCode"></param>
        /// <returns></returns>
        public bool BeifenTestData(string testCode)
        {
            return dal.BeifenTestData(testCode);
        }

        /// <summary>
        /// 强制退回化验数据审核
        /// </summary>
        /// <param name="TestCode"></param>
        /// <returns></returns>
        public string TuiHuiAuditData(string testCode)
        {
            return dal.TuiHuiAuditData(testCode);
        }

        public List<V_STATS_LMS_PLAN_RESULTModel> GetList(ref GridPager pager, string userid, string testcode, string MATERIEL_ID, string startdate, string enddate, string type, int queryState = -1, string TYPE_STR = "", string batchCode = "", string BATCH_TYPE = "")
        {
            try
            {
                using (DBContainer db = new DBContainer())
                {
                    IQueryable<V_STATS_LMS_PLAN_RESULT> queryData = (from r in db.V_STATS_LMS_PLAN_RESULT
                                                                     join c in db.V_FLOW_STEPINFO
                                                                     on r.AUDIT_ID equals c.ID into empflow
                                                                     from f in empflow.DefaultIfEmpty()
                                                                     where r.APPROVAL_STATUS > 1 && r.BATCH_TYPE.Contains(BATCH_TYPE) && (queryState == -1 || r.APPROVAL_STATUS == queryState)
                                                                     select r).Distinct();//c.USERID == userid &&

                    if (!string.IsNullOrEmpty(testcode))
                    {
                        queryData = queryData.Where(m => m.TEST_CODE.Contains(testcode));
                    }
                    if (!string.IsNullOrEmpty(MATERIEL_ID) && !MATERIEL_ID.Contains("=== 物料 ==="))
                    {
                        queryData = queryData.Where(m => m.MATERIEL_NAME == MATERIEL_ID);
                    }
                    if (!string.IsNullOrEmpty(TYPE_STR))
                    {
                        queryData = queryData.Where(m => m.TYPE_STR == TYPE_STR);
                    }
                    if (!string.IsNullOrEmpty(batchCode))
                    {
                        queryData = queryData.Where(m => m.BATCH_CODE == batchCode);
                    }
                    if (!string.IsNullOrEmpty(startdate))
                    {
                        DateTime dStartDate = DateTime.Parse(startdate).Date;
                        queryData = queryData.Where(m => m.UPDATE_TIME >= dStartDate);
                    }
                    if (!string.IsNullOrEmpty(enddate))
                    {
                        DateTime dEndDate = DateTime.Parse(enddate).Date.AddDays(1);
                        queryData = queryData.Where(m => m.UPDATE_TIME <= dEndDate);
                    }


                    //IQueryable<YANX_RECORD> yxData = (from r in db.YANX_RECORD
                    //                                                 where r.AUDIT_STATUS== "审核通过" 
                    //                                                 select r).Distinct(); 

                    pager.totalRows = queryData.Count();
                    //排序
                    queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                    //return TransHelper.TransExpList<V_LMS_RESULT_AUDIT, V_LMS_RESULT_AUDITModel>(queryData.ToList());
                    var returnData = (from r in queryData
                                      join c in db.Flow_FormContent
                                      on r.AUDIT_ID equals c.Id into tmpcont
                                      join dd in db.V_LMS_RESULT //吴幽  新增
                                      on r.TEST_CODE equals dd.TEST_CODE //吴幽  新增

                                      //join yx in yxData.DefaultIfEmpty()//吴幽  新增
                                      //on r.TEST_CODE equals yx.TEST_CODE 

                                      from f in tmpcont.DefaultIfEmpty()
                                      where dd.TEST_STATE == 1 && dd.TEST_TYPE_STR == "最终指标值"
                                      select new V_STATS_LMS_PLAN_RESULTModel
                                      {
                                          BATCH_CODE = r.BATCH_CODE,
                                          AUDIT_ID = r.AUDIT_ID,
                                          TEST_CODE = r.TEST_CODE,
                                          UPDATE_TIME = r.UPDATE_TIME,
                                          STYPE_STR = r.STYPE_STR,
                                          TEST_TYPE_STR = r.TEST_TYPE_STR,
                                          TEST_MODE_STR = r.TEST_MODE_STR,
                                          MT = r.MT,
                                          MAD = r.MAD,
                                          AD = r.AD,
                                          VDAF = r.VDAF,
                                          STD = r.STD,
                                          G = r.G,
                                          Y = r.Y,
                                          X = r.X,
                                          A = r.A,
                                          B = r.B,
                                          QNETAR_KCAL = r.QNETAR_KCAL,
                                          APPROVAL_STATUS = r.APPROVAL_STATUS,
                                          TEMPLATE_ID = (f == null) ? r.TEMPLATE_ID : f.FormId,
                                          AUDIT_USER_ID = (f == null) ? null : f.CustomMember,
                                          AUDIT_TIME = r.AUDIT_TIME,
                                          MATERIEL_NAME = r.MATERIEL_NAME,
                                          TYPE_STR = r.TYPE_STR,
                                          //以下 吴幽新增
                                          SMALL = dd.SMALL,
                                          SMEDIUN = dd.SMEDIUN,
                                          MEDIUM = dd.MEDIUM,
                                          LARGE = dd.LARGE,
                                          CRI = dd.CRI,
                                          CSR = dd.CSR,
                                          M40 = dd.M40,
                                          M10 = dd.M10,
                                          JTXXLARGE = dd.JTXXLARGE,
                                          JTXLARGE = dd.JTXLARGE,
                                          JTLARGE = dd.JTLARGE,
                                          JTMEDIUM = dd.JTMEDIUM,
                                          JTSMALL = dd.JTSMALL,
                                          //YXVALUE = yx.ITEM_VALUE
                                      }).OrderByDescending(a => a.AUDIT_TIME).Distinct().ToList();

                    return returnData;

                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public List<V_LMS_RESULT_AUDITModel> GetList(ref GridPager pager, string userid, string testcode, string startdate, string enddate)
        {
            using (DBContainer db = new DBContainer())
            {
                IQueryable<V_LMS_RESULT_AUDIT> queryData = (from r in db.V_LMS_RESULT_AUDIT
                                                            join c in db.V_FLOW_STEPINFO
                                                            on r.AUDIT_ID equals c.ID
                                                            where c.USERID == userid && r.APPROVAL_STATUS > 1
                                                            select r).Distinct();
                if (!string.IsNullOrEmpty(testcode))
                {
                    queryData = queryData.Where(m => m.TEST_CODE == testcode);
                }
                if (!string.IsNullOrEmpty(startdate))
                {
                    DateTime dStartDate = DateTime.ParseExact(startdate, "yyyy-MM-dd", null);
                    queryData = queryData.Where(m => m.UPDATE_TIME >= dStartDate);
                }
                if (!string.IsNullOrEmpty(enddate))
                {
                    DateTime dEndDate = DateTime.ParseExact(enddate, "yyyy-MM-dd", null);
                    queryData = queryData.Where(m => m.UPDATE_TIME <= dEndDate);
                }

                pager.totalRows = queryData.Count();
                //排序
                queryData = LinqHelper.SortingAndPaging(queryData, pager.sort, pager.order, pager.page, pager.rows);
                //return TransHelper.TransExpList<V_LMS_RESULT_AUDIT, V_LMS_RESULT_AUDITModel>(queryData.ToList());
                return (from r in queryData
                        join c in db.Flow_FormContent
                        on r.AUDIT_ID equals c.Id
                        select new V_LMS_RESULT_AUDITModel
                        {
                            AUDIT_ID = r.AUDIT_ID,
                            TEST_CODE = r.TEST_CODE,
                            UPDATE_TIME = r.UPDATE_TIME,
                            STYPE = r.STYPE,
                            STYPE_STR = r.STYPE_STR,
                            TEST_TYPE = r.TEST_TYPE,
                            TEST_TYPE_STR = r.TEST_TYPE_STR,
                            TEST_MODE_STR = r.TEST_MODE_STR,
                            MT = r.MT,
                            MAD = r.MAD,
                            AAD = r.AAD,
                            AD = r.AD,
                            AAR = r.AAR,
                            VAD = r.VAD,
                            VD = r.VD,
                            VAR = r.VAR,
                            VDAF = r.VDAF,
                            FCAD = r.FCAD,
                            CRC = r.CRC,
                            STAD = r.STAD,
                            STD = r.STD,
                            STAR = r.STAR,
                            STDAF = r.STDAF,
                            QBAD = r.QBAD,
                            QGRAD = r.QGRAD,
                            QGRD = r.QGRD,
                            QNETAR_MJ = r.QNETAR_MJ,
                            QNETAR_KCAL = r.QNETAR_KCAL,
                            HAD = r.HAD,
                            APPROVAL_STATUS = r.APPROVAL_STATUS,
                            TEMPLATE_ID = r.TEMPLATE_ID,
                            AUDIT_USER_ID = c.CustomMember,
                            AUDIT_TIME = r.AUDIT_TIME
                        }).ToList();


            }
        }

        public V_LMS_RESULT_AUDITModel GetViewById(string testcode)
        {
            using (DBContainer db = new DBContainer())
            {
                IQueryable<V_LMS_RESULT_AUDIT> queryData = db.V_LMS_RESULT_AUDIT.AsQueryable<V_LMS_RESULT_AUDIT>();
                return TransHelper.TransExp<V_LMS_RESULT_AUDIT, V_LMS_RESULT_AUDITModel>(queryData.Where(p => p.TEST_CODE == testcode).First());
            }
        }
    }
}
